package org.dbrd.detector.tfidf;

import java.util.HashMap;
import java.util.Map;


public class IDFCollection {

	private static class Value {

		private int frequency;
		
		private int countAcrossCollection;
		
		private double idf;

		public Value(int frequency) {
			this.frequency = frequency;
		}

		public void increaseFrequency() {
			this.frequency++;
		}
		
		public void increaseCountAcrossCollection(int countInDocument) {
			this.countAcrossCollection += countInDocument;
		}
		
		public int toIntValue() {
			return this.frequency;
		}
	}
	
	
	private Map<String, Value> idfMap = new HashMap<String, Value>();
	
	private IIDFCalculator idfCalculator;

	private int documentCount;
	
	public IDFCollection() {
		this.idfCalculator = new DefaultIDFCalculator();
	}
	
//	public IDFCollection(IIDFCalculator idfCalculator) {
//		this.idfCalculator = idfCalculator;
//	}
	
	/**
	 * add a term to the TFCollection. 
	 * the corresponding tf will be increased by 1.
	 * @param term
	 * @return
	 */
	private void addTerm(String term) {
		Value value = this.idfMap.get(term);
		if (value == null) {
			value = new Value(1);
			this.idfMap.put(term, value);
		} else {
			value.increaseFrequency();
		}
	}
	
	public void addTerms(String[] terms) {
		for (String string : terms) {
			this.addTerm(string);
		}
	}
	
	
//	public int getFrequency(String term) {
//		Value value = this.idfMap.get(term);
//		if (value == null) {
//			return 0;
//		} else {
//			return value.frequency;
//		}
//	}
	
	public double getIDF(String term) {
		Value value = this.idfMap.get(term);
		if (value == null) {
			return 0; 
		} else {
			return value.idf;
		}
	}

//	public void clear() {
//		this.idfMap.clear();
//	}

//	public String[] getTerms() {
//		Set<String> keys = this.idfMap.keySet();
//		return keys.toArray(new String[keys.size()]);
//	}

	public void calculateIDF(int documentCount) {
		if (this.idfCalculator == null) {
			throw new RuntimeException("idfCalculator is null.");
		}
		this.documentCount = documentCount;
		for (Value value: this.idfMap.values()) {
			value.idf = this.idfCalculator.calculate(documentCount, value.frequency);
		}
	}

	public int getDocumentCount() {
		return documentCount;
	}
	
	
}
